package com.by_man.presenter.module_bluetooth;


import android.annotation.TargetApi;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.by_man.presenter.R;
import com.by_man.presenter.module_health_management.measure_blood_pressure.MeasureBloodPressureActivity;

import java.util.ArrayList;
import java.util.List;

public class DeviceScanActivity extends ListActivity
{
    private List<BluetoothDevice> list=new ArrayList<BluetoothDevice>();
    private static final int REQUEST_ENABLE_BT = 1;
    private static final long SCAN_PERIOD = 10000L;//搜索周期
    private ListView listView;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private boolean mScanning;



    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void onCreate(Bundle paramBundle)
    {
        super.onCreate(paramBundle);
        this.mHandler = new Handler();

        if (!getPackageManager().hasSystemFeature("android.hardware.bluetooth_le"))
        {
            Toast.makeText(this, "ble_not_supported",Toast.LENGTH_SHORT).show();
            finish();
        }
        this.mBluetoothAdapter = ((BluetoothManager)getSystemService(BLUETOOTH_SERVICE)).getAdapter();
        if (this.mBluetoothAdapter == null)
        {
            Toast.makeText(this, "error_bluetooth_not_supported", Toast.LENGTH_SHORT).show();
            finish();
        }

    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(boolean paramBoolean)  //扫描设备
    {

        if (paramBoolean)
        {
            this.mHandler.postDelayed(new Runnable()
            {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
                public void run()
                {

                    DeviceScanActivity.this.mScanning = false;
                    DeviceScanActivity.this.mBluetoothAdapter.stopLeScan(DeviceScanActivity.this.mLeScanCallback);
                    DeviceScanActivity.this.invalidateOptionsMenu();
                }
            }
                    , 60000L);
            this.mScanning = true;
            this.mBluetoothAdapter.startLeScan(this.mLeScanCallback);
        }
        else
        {
            invalidateOptionsMenu();
            this.mScanning=false;
            this.mBluetoothAdapter.stopLeScan(this.mLeScanCallback);
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback()//找到ble
    {

        public void onLeScan(final BluetoothDevice paramAnonymousBluetoothDevice, int paramAnonymousInt, final byte[] paramAnonymousArrayOfByte)
        {
            DeviceScanActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLeDeviceListAdapter.addDevice(paramAnonymousBluetoothDevice);
                    mLeDeviceListAdapter.notifyDataSetChanged();

                }
            }); //更新UI线程  匿名蓝牙参数
        }
    };




    protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)//回调函数完成子模块，并返回数据
    {
        if ((paramInt1 == 1) && (paramInt2 == 0))
            finish();
        else
        {
            super.onActivityResult(paramInt1, paramInt2, paramIntent);
            return;
        }
    }





    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    protected void onListItemClick(ListView paramListView, View paramView, int paramInt, long paramLong)//listview中点击事件的响应
    {
        BluetoothDevice localBluetoothDevice = this.mLeDeviceListAdapter.getDevice(paramInt);
        if (localBluetoothDevice == null);
        else
        {

            Intent localIntent = new Intent(this, BppDemo.class);
            localIntent.putExtra("DEVICE_NAME", localBluetoothDevice.getName());
            localIntent.putExtra("DEVICE_ADDRESS", localBluetoothDevice.getAddress());
            if (this.mScanning)
            {
                this.mBluetoothAdapter.stopLeScan(this.mLeScanCallback);
                this.mScanning = false;
            }
            startActivity(localIntent);
            return;
        }
    }



    protected void onPause()//当前Activity被其他Activity覆盖其上或被锁屏：系统会调用onPause方法，暂停当前Activity的执行。

    {
        super.onPause();
        scanLeDevice(false);
        this.mLeDeviceListAdapter.clear();
    }

    protected void onResume()//当前Activity由被覆盖状态回到前台或解锁屏：系统会调用onResume方法，再次进入运行状态。
    {
        super.onResume();
        if ((!this.mBluetoothAdapter.isEnabled()) && (!this.mBluetoothAdapter.isEnabled()))
            startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
        this.mLeDeviceListAdapter = new LeDeviceListAdapter();
        setListAdapter(this.mLeDeviceListAdapter);
        scanLeDevice(true);
    }

    private class LeDeviceListAdapter extends BaseAdapter//获取蓝牙设备列表
    {

        private LayoutInflater mInflator = DeviceScanActivity.this.getLayoutInflater();
        private ArrayList<BluetoothDevice> mLeDevices = new ArrayList<BluetoothDevice>();


        public LeDeviceListAdapter()
        {
        }

        public void addDevice(BluetoothDevice paramBluetoothDevice)//增加设备
        {
            if (!this.mLeDevices.contains(paramBluetoothDevice))
                this.mLeDevices.add(paramBluetoothDevice);
        }

        public void clear()//清空设备
        {
            this.mLeDevices.clear();
        }

        public int getCount()//得到设备数量
        {
            return this.mLeDevices.size();
        }

        public BluetoothDevice getDevice(int paramInt)
        {
            return this.mLeDevices.get(paramInt);

        }

        public Object getItem(int paramInt)
        {
            return this.mLeDevices.get(paramInt);
        }

        public long getItemId(int paramInt)
        {
            return paramInt;
        }

        public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
        {


            DeviceScanActivity.ViewHolder localViewHolder;
            BluetoothDevice localBluetoothDevice;
            if (paramView == null)
            {

                paramView = this.mInflator.inflate(R.layout.activity_device_scan1,null);
                localViewHolder = new DeviceScanActivity.ViewHolder();
                localViewHolder.deviceAddress = ((TextView)paramView.findViewById(R.id.deviceAddress));
                localViewHolder.deviceName = ((TextView)paramView.findViewById(R.id.deviceName));
                paramView.setTag(localViewHolder);
                localBluetoothDevice = this.mLeDevices.get(paramInt);
                String str = localBluetoothDevice.getName();
                if ((str == null) || (str.length() <= 0))
                {
                    localViewHolder.deviceName.setText(str);
                }
                else
                {
                    localViewHolder.deviceAddress.setText(localBluetoothDevice.getAddress());
                    localViewHolder = (DeviceScanActivity.ViewHolder)paramView.getTag();
                    localViewHolder.deviceName.setText(localBluetoothDevice.getName());//unknown_device = 2130968586;
                    //break;
                }
            }
            return paramView;

        }
    }

    static class ViewHolder
    {
        TextView deviceAddress;
        TextView deviceName;


    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键
            Intent intent=new Intent(DeviceScanActivity.this,MeasureBloodPressureActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }
}